package com.ranqianhui.randyojcodesandbox.utils;

import cn.hutool.core.util.StrUtil;
import com.ranqianhui.randyojcodesandbox.model.ExecuteMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 进程工具类
 */
public class ProcessUtils {

    /**
     * 返回执行进程的状态和输出
     *
     * @param runProcess
     * @param opName
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            StopWatch stopWatch=new StopWatch();
            stopWatch.start();
            //等待程序执行，获取错误码
            int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            if (exitValue == 0) {
                System.out.println(opName + "成功");
                //分配获取进程的正常输出流
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                List<String> outputStrList=new ArrayList<>();
                //逐行读取
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    outputStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outputStrList,"\n"));
                bufferedReader.close();
            } else {
                System.out.println(opName + "失败，错误码：" + exitValue);
                //分配获取进程的正常输出流
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                List<String> outputStrList=new ArrayList<>();
                //逐行读取
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    outputStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outputStrList,"\n"));

                //分配获取进程的错误输出流
                BufferedReader errorbufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder compileErrorOutputStringBuilder = new StringBuilder();
                //逐行读取
                List<String> erroroutputStrList=new ArrayList<>();
                //逐行读取
                String errorcompileOutputLine;
                while ((errorcompileOutputLine = errorbufferedReader.readLine()) != null) {
                    erroroutputStrList.add(errorcompileOutputLine);
                }
                executeMessage.setErrorMessage(StringUtils.join(erroroutputStrList,"\n"));
                errorbufferedReader.close();
                bufferedReader.close();
                stopWatch.stop();
                executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        runProcess.destroy();
        return executeMessage;
    }

    /**
     * 执行交互式进程并获取信息
     *
     * @param runProcess
     * @param opName
     * @return
     */

    public static ExecuteMessage runInteractProcessAndGetMessage(Process runProcess, String opName,String args) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            //向控制台输入程序
            OutputStream outputStream = runProcess.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            String[] s = args.split(" ");
            String join = StrUtil.join("\n", s)+"\n";
            outputStreamWriter.write(join);
            //相当于按了回车
            outputStreamWriter.flush();

            InputStream inputStream = runProcess.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            //逐行读取
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine);
            }
            executeMessage.setMessage(compileOutputStringBuilder.toString());
            //资源的回收
            inputStream.close();
            outputStreamWriter.close();
            outputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
        runProcess.destroy();
        return executeMessage;
    }
}
